<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use think\exception\ValidateException;
use EasyWeChat\Factory;


// 话题管理
class Topic extends BaseController
{

    public function index()
    {
        //获取帖子话题类型
        $data = Db::name('topic_type')
            ->where('status', '=', 1)
            ->field('id, name')
            ->select();
        View::assign('data', $data);
        return View::fetch();
    }


    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $where = [];

        if (isset($get['status'])) {
            if (!empty($get['status'])) {
                $where[] = ['a.status', '=', $get['status']];
            } else {
                $where[] = ['a.status', 'in', [1,2]];
            }
        } else {
            $where[] = ['a.status', 'in', [1,2]];
        }


        if (isset($get['top'])) {
            if (!empty($get['top'])) {
                $where[] = ['a.top', '=', $get['top']];
            }
        }

        if (isset($get['tj'])) {
            if (!empty($get['tj'])) {
                $where[] = ['a.tj', '=', $get['tj']];
            }
        }

        if (isset($get['keys'])) {
            if (!empty($get['keys'])) {
                $where[] = ['a.content|b.name', 'like', '%'.$get['keys'].'%'];
            }
        }

        if (isset($get['type'])) {
            if (!empty($get['type'])) {
                $type = $get['type'];
                $where[] = ['','EXP',Db::raw('FIND_IN_SET("'.$type.'",a.type)')];
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }

        if ( !empty($get['field']) && !empty($get['order'])) {
            $field = $get['field'];
            $sort = $get['order'];
        } else {
            $field = 'add_time';
            $sort = 'desc';
        }

        $total = Db::table('o_topic')
            ->alias('a')
            ->join('o_members b', 'b.id=a.uid')
            ->where($where)
            ->count();

        $rows = Db::table('o_topic')
            ->alias('a')
            ->join('o_members b', 'b.id=a.uid')
            ->where($where)
            ->field('a.id, a.uid, a.type, a.content, a.status, a.add_time, a.forward, a.coll, a.hits, a.huifu, a.zan, a.hot, a.tj, a.lock, a.top, b.name as username, b.department_name')
            ->page($get['page'], $get['limit'])
            ->order("$field", "$sort")
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $data = Db::name('topic_type')->where('id', 'in', $v['type'])->column('name');
            if ($data) {
                $v['type_name'] = mb_substr(implode('/',$data), 0, 20).'...';
            }else{
                $v['type_name'] = '';
            }

            $content = mb_substr(strip_tags($v['content']),0,20,'utf-8');

            $v['content'] = preg_replace_callback('/@E(.{6}==)/', function($r) {return base64_decode($r[1]);}, $content);
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    // 置顶操作
    public function top(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }

        try {
            $inf = Db::name('topic')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if ($inf['lock'] == 2) {
                return $this->outputAjax('帖子已锁定，本次操作无效！');
            }

            if (!in_array($inf['top'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $status = $inf['top'] == 1 ? 2 : 1;

            $update = array(
                'top'=> $status,
            );
            if(Db::name('topic')->where('id', '=', $id)->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    // 推荐操作
    public function recommend(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }

        try {
            $inf = Db::name('topic')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if ($inf['lock'] == 2) {
                return $this->outputAjax('帖子已锁定，本次操作无效！');
            }

            if (!in_array($inf['tj'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $status = $inf['tj'] == 1 ? 2 : 1;

            $update = array(
                'tj' => $status,
            );
            if(Db::name('topic')->where('id', '=', $id)->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    // 锁定操作
    public function lock(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }

        try {
            $inf = Db::name('topic')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['lock'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $status = $inf['lock'] == 1 ? 2 : 1;

            $update = array(
                'lock' => $status,
            );
            if(Db::name('topic')->where('id', '=', $id)->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    // 关闭操作
    public function toggle(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');
        if (!$id) {
            return $this->outputAjax();
        }

        try {
            $inf = Db::name('topic')->find($id);

            if (empty($inf)) {
                return $this->outputAjax('参数错误！');
            }

            if (!in_array($inf['status'], array(1, 2))) {
                return $this->outputAjax('参数错误[1]！');
            }

            $status = $inf['status'] == 1 ? 2 : 1;

            $update = array(
                'status' => $status,
            );
            if(Db::name('topic')->where('id', '=', $id)->update($update)) {
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        try {
            //+帖子基本信息
            $inf = Db::name('topic')->where('id', '=', $id)->find();

            if (!$inf) {
                return $this->outputAjax('参数错误！');
            }

            if (!Db::name('topic')->where('id', '=', $id)->update(['status' => 3])) {
                return $this->outputAjax('删除失败！');
            }
            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function getQrCode(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->param('id');

        try {

            $app = Factory::miniProgram($this->mini_config);

            $page = 'pages/MomentsBox/pages/shareMomentsInfo/shareMomentsInfo';
            $response = $app->app_code->getUnlimit($id, [
                'page'  => $page,
                'width' => 300,
            ]);

            $time = time();
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(runtime_path().'/storage', $time.'.png');
            }

            $blob = new Upload();
            $res = $blob->uploadBlob(runtime_path().'/storage/'.$filename, $filename, 'image/png', 'small');
            if ($res['code'] == 200) {
                $qr = $res['data'];
            } else {
                $qr = '';
            }
            //删除文件
            unlink(runtime_path() . 'storage/' . $filename);
            return $this->outputAjax('获取成功', 0, ['url' => $qr]);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    public function export(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $get = $request->get();

        if (!empty($get['status'])) {
            $where[] = ['a.status', '=', $get['status']];
        } else {
            $where[] = ['a.status', 'in', [1,2]];
        }


        if (!empty($get['top'])) {
            $where[] = ['a.top', '=', $get['top']];
        }

        if (!empty($get['tj'])) {
            $where[] = ['a.tj', '=', $get['tj']];
        }

        if (!empty($get['keys'])) {
            $where[] = ['a.content|b.name', 'like', '%'.$get['keys'].'%'];
        }

        if (!empty($get['type'])) {
            $type = $get['type'];
            $where[] = ['','EXP',Db::raw('FIND_IN_SET("'.$type.'",a.type)')];
        }

        if (!empty($get['time'])) {
            $t = explode(' - ', $get['time']);
            $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
        }

        ob_end_clean ();
        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '帖子数据'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['话题分类', '帖子内容', '发帖人caroid', '发帖人姓名', '部门', '转发', '收藏', '热度', '浏览量', '回复数', '点赞数', '发布时间 ']);

        $total = Db::table('o_topic')
            ->alias('a')
            ->join('o_members b', 'b.id=a.uid')
            ->where($where)
            ->count();
        $nums = 1000; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::table('o_topic')
                ->alias('a')
                ->join('o_members b', 'b.id=a.uid')
                ->where($where)
                ->field('a.id, a.uid, a.type, a.content, a.status, a.add_time, a.forward, a.coll, a.hits, a.huifu, a.zan, a.hot, a.tj, a.lock, a.top, b.userid, b.name as username, b.department_name')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as &$value) {
                $data = Db::name('topic_type')->where('id', 'in', $value['type'])->column('name');
                if ($data) {
                    $type_name = mb_substr(implode('/',$data), 0, 20).'...';
                }else{
                    $type_name = '';
                }

                $content = mb_substr(strip_tags($value['content']),0,20,'utf-8');

                $content = preg_replace_callback('/@E(.{6}==)/', function($r) {return base64_decode($r[1]);}, $content);

                $count = mb_strlen($value['userid']);
                if ($count == 6) {
                    if (is_numeric($value['userid'])) {
                        $userid = "'00".$value['userid'];
                    } else {
                        $userid = $value['userid'];
                    }
                } else {
                    $userid = $value['userid'];
                }

                $arr = [
                    $type_name,
                    $content,
                    $userid,
                    $value['username'],
                    $value['department_name'],
                    $value['forward'],
                    $value['coll'],
                    $value['hot'],
                    $value['hits'],
                    $value['huifu'],
                    $value['zan'],
                    date('Y-m-d H:i',$value['add_time'])
                ];
                fputcsv($fp, $arr);
            }
            //每1千条数据就刷新缓冲区
            flush();
        }
    }


    public function view(Request $request)
    {
        $id = $request->param('id');

        $inf = Db::name('topic')
            ->field('id, uid, type, content, relation')
            ->find($id);

        //+帖子类型
        $type_name= Db::name('TopicType')->where(['id'=>['in',$inf['type']]])->column('name');
        if ($type_name) {
            $inf['type_name'] = implode('/',$type_name);
        }else{
            $inf['type_name'] = '';
        }
        //+发布人
        $user = Db::name('members')->where('id', $inf['uid'])->find();
        $inf['username'] = $user['name'];


        //+@的人
        $relations = explode(',',$inf['relation']);
        $inf['relation_user'] = [];
        foreach ($relations as $value){
            $user = Db::name('members')->find($value);
            if($user){
                $inf['relation_user'][] = $user;
            }
        }
        $inf['midea'] = $this->getMidea($inf['id']);
        View::assign('id',$id);
        View::assign('inf',$inf);
        return View::fetch();
    }

    public function getTotalList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->get('id');

        $inf = Db::name('topic')
            ->field('id, zan, coll, forward, hits, huifu')
            ->find($id);

        $data = [
            [
                'name' => '点赞数',
                'type' => 1,
                'id' => 1,
                'total' => $inf['zan']
            ],
            [
                'name' => '收藏数',
                'type' => 2,
                'id' => 2,
                'total' => $inf['coll']
            ],
            [
                'name' => '转发数',
                'type' => 3,
                'id' => 3,
                'total' => $inf['forward']
            ],
            [
                'name' => '浏览量',
                'type' => 4,
                'id' => 4,
                'total' => $inf['hits']
            ],
            [
                'name' => '评论量',
                'type' => 5,
                'id' => 5,
                'total' => $inf['huifu']
            ]
        ];

        $datas = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $data
        );
        return json($datas);
    }


    public function exportTotal(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $get = $request->get();

        $list = [];

        $where = [];
        $where[] = ['aid', '=', $get['id']];
        $where[] = ['type', '=', 1];


        switch ($get['type'])
        {
            case 3:
                $list = Db::name('forward')->where($where)->select();
                break;
            case 2:
                $list = Db::name('collection')->where($where)->select();
                break;
            case 4:
                $list = Db::name('show_logs')->where($where)->select();
                break;
            case 5:
                $where[] = ['pid', '=', 0];
                $list = Db::name('comment')->where($where)->select();
                break;
            case 1:
                $list = Db::name('zan')->where($where)->select();
                break;
            default:;
        }


        $newList = [];
        foreach ($list as $key => $value){
            $members = Db::name('members')->where('id', $value['uid'])->find();
            $count = mb_strlen($members['userid']);
            if ($count == 6) {
                if (is_numeric($members['userid'])) {
                    $newList[$key]['userid'] = "'00".$members['userid'];
                } else {
                    $newList[$key]['userid'] = $members['userid'];
                }
            } else {
                $newList[$key]['userid'] = $members['userid'];
            }

            $newList[$key]['name'] = $members['name'];
            $newList[$key]['add_time'] = $value['add_time'];
        }
        ob_end_clean ();

        $fileName = '帖子数据'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['订阅人carolid', '姓名', '时间']);


        foreach ($newList as &$value) {
            if(!$value['userid']) {
                continue;
            } else {
                $count = mb_strlen($value['userid']);
                if ($count == 6) {
                    if (is_numeric($value['userid'])) {
                        $userid = "00".$value['userid'];
                    } else {
                        $userid = $value['userid'];
                    }
                } else {
                    $userid = $value['userid'];
                }

                $arr = [
                    $userid,
                    $value['name'],
                    date('Y-m-d H:i',$value['add_time'])
                ];
                fputcsv($fp, $arr);
            }
        }
        flush();
    }


    public function getCommentList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->get('id');
        $rows = Db::name('comment')
            ->where('type', '=', 1)
            ->where('pid', '=', 0)
            ->where('aid', '=', $id)
            ->where('status', '=', 1)
            ->select()
            ->toArray();

        foreach ($rows as &$value) {
            $username = Db::name('members')
                ->where('id', '=', $value['uid'])
                ->value('name');
            $value['username'] = $username;

            if ($value['pid'] == 0) {
                $value['zan'] = Db::name('zan')->where('type', '=', 2)->where('aid', '=', $value['id'])->count();
            }
            if ($value['status'] == 2) {
                $value['content'] = '本条评论内容已删除';
            }
            $value['content'] = preg_replace_callback('/@E(.{6}==)/', function($r) {return base64_decode($r[1]);}, $value['content']);
            $value['add_time2'] = formatdate($value['add_time']);
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $rows
        );
        return json($data);
    }

    public function deleteComment(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->post('id');
        Db::startTrans();
        try {
            if (!Db::name('comment')->where('id', '=', $id)->update(['status' => 2])) {
                Db::rollback();
                return $this->outputAjax('删除失败');
            }

            $res = Db::name('comment')
                ->where('pid', '=', $id)
                ->where('status', '=', 1)
                ->find();

            if ($res) {
                if (!Db::name('comment')->where('pid', '=', $id)->update(['status' => 2])) {
                    Db::rollback();
                    return $this->outputAjax('删除失败');
                }
            }

            Db::commit();
            return $this->outputAjax('删除成功！', 0);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }

    }

    protected function getMidea($id)
    {

        $data = Db::name('topic_media')->where(['tid'=>$id])->select()->toArray();

        if ($data) {
            $imgs = [];
            foreach ($data as $key => $value) {

                if ($value['type'] == 2) {

                    $t['type'] = 'video';

                    $t['path'] = strpos($value['path'],'http') === false ? request()->domain().$value['path']:$value['path'];

                    $t['img'] = strpos($value['path2'],'http') === false ? request()->domain().$value['path2'] : $value['path2'];

                    return $t;

                }else{

                    $imgs[] = strpos($value['path'],'http') === false ? request()->domain().$value['path']:$value['path'];

                }

            }

            $t['type'] = 'img';

            $t['paths'] = $imgs;

            return $t;

        }else{

            return [];

        }

    }


    public function logs(Request $request)
    {
        $get = $request->get();

        View::assign('id', $get['id']);
        View::assign('type', $get['type']);

        return View::fetch();
    }

    public function getLogsList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $list = [];

        $where = [];
        $where[] = ['aid', '=', $get['id']];
        $where[] = ['type', '=', 1];


        switch ($get['type'])
        {
            case 3:
                $list = Db::name('forward')->where($where)->select();
                break;
            case 2:
                $list = Db::name('collection')->where($where)->select();
                break;
            case 4:
                $list = Db::name('show_logs')->where($where)->select();
                break;
            case 5:
                $where[] = ['pid', '=', 0];
                $list = Db::name('comment')->where($where)->select();
                break;
            case 1:
                $list = Db::name('zan')->where($where)->select();
                break;
            default:;
        }


        $newList = [];
        foreach ($list as $key => $value){
            $members = Db::name('members')->where('id', '=', $value['uid'])->find();
            $count = mb_strlen($members['userid']);
            if ($count == 6) {
                if (is_numeric($members['userid'])) {
                    $newList[$key]['userid'] = '00'.$members['userid'];
                } else {
                    $newList[$key]['userid'] = $members['userid'];
                }
            } else {
                $newList[$key]['userid'] = $members['userid'];
            }

            $newList[$key]['name'] = $members['name'];
            $newList[$key]['add_time'] = $value['add_time'];
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $newList
        );
        return json($data);
    }


    public function show(Request $request)
    {
        $get = $request->get();

        View::assign('id', $get['id']);
        return View::fetch();
    }

    public function getReplyList(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $rows = Db::name('comment')
            ->where('pid', '=', $get['id'])
            ->select();

        foreach ($rows as &$value) {
            $name = Db::name('members')
                ->where('id', '', $value['uid'])
                ->value('name');
            $value['username'] = $name;

            if ($value['status'] == 2) {
                $value['content'] = '本条评论内容已删除';
            }
            $value['add_time2'] = formatdate($value['add_time']);
            $value['content']= preg_replace_callback('/@E(.{6}==)/', function($r) {return base64_decode($r[1]);}, $value['content']);
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => 0,
            'data'=> $rows
        );
        return json($data);
    }
}